package com.jt.email;

import com.jt.pojo.Email;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

@RestController
@CrossOrigin
public class SendEmail {
    @RequestMapping("/email")
    public String sendEmail(@RequestBody Email email) {
        String to = email.getToEmail();
        String from = "1942235754@qq.com";
        String host = "smtp.qq.com";
        Properties properties = System.getProperties();
        properties.setProperty("mail.smtp.host", host);
        properties.put("mail.smtp.auth", "true");
        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("1942235754@qq.com", "gmoophonivfwjefc");
            }
        });
        try {
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(from));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            message.setSubject(email.getUsername());
            message.setContent("<h1>姓名:" + email.getUsername() + "</h1>"
                    + "<h2>电话:"+email.getPhone() + "</h2>"
                    + "<h2>城市:"+email.getInAddr() + "</h2>"
                    + "<h2>备注:"+email.getBz() + "</h2>"
                    + "<h2>住址:"+email.getAddr() + "</h2><br/>"
                    + "<h3>"+email.getContent()+"</h3>", "text/html;charset=utf-8");
            Transport.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
        }

        return "成功!";
    }
}
